package com.sgb.kjwl.view.ui.activity.self.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.GridLayoutManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityMachinePublishOutBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.jicai.entity.FilterEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.link.entity.PublicTypeEntity;
import com.sgb.kjwl.model.entity.SuccessEntity;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddMachineOutEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.DictEntity;
import com.sgb.kjwl.model.entity.user.PublicAttrEntity;
import com.sgb.link.entity.ReturnTypeEntity;
import com.sgb.kjwl.model.entity.user.ServiceEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.PickEvent;
import com.sgb.kjwl.view.event.self.MachinePublishEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.sgb.kjwl.view.ui.activity.self.authentication.CommitSuccessActivity;
import com.sgb.kjwl.view.ui.adapter.self.publish.ImageAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.view.widget.TimeRangePopWindow4;
import com.sgb.kjwl.viewmodel.self.publish.MachinePublishOutModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.MDateUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.NullStringToEmptyAdapterFactory;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import static com.swgk.core.event.EventConstant.EVENT_PUBLISH_MACHINE_ATTR;
import static com.swgk.core.event.EventConstant.EVENT_PUBLISH_MACHINE_RETURN;
import static com.sgb.kjwl.view.event.SuccessType.SUCC_MACHINE_OUT;

/**
 * 机械出租发布
 */
@Deprecated
public class MachinePublishOutActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    private ActivityMachinePublishOutBinding binding;
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static final int MSG_LOAD_DATA_UNIT = 0x0004;
    private static final int MSG_LOAD_SUCCESS_UNIT = 0x0005;
    private boolean isLoaded = false;
    private boolean isLoadedUnit = false;
    private Intent intent;
    private Bundle bundle;
    private List<PickSelectEntity> serviceEntities;
    //图片上传
    private List<LocalMedia> selectList = new ArrayList<>();
    private ImageAdapter adapter;
    private List<String> urls;
    private List<File> fileList;
    public int imgTotal;
    private int currentImgNum;
    private List<String> uploadImgList = new ArrayList<>();
    private List<PickSelectEntity> driverDatas, invoiceDatas, invoiceGGDatas;
    private List<PickSelectEntity> tariffDatas = new ArrayList<>();
    //接口机械类型数据
    private List<PublicTypeEntity<List<PublicTypeEntity>>> publicTypeEntityList;
    //获取的属性实体
    private List<FilterEntity<List<FilterEntity>>> attrList;
    //单位实体列表
    private List<DictEntity> dictEntityList;
    //单位食堂列表
    private List<DictEntity> dictEntityListnew = new ArrayList<>();
    //选择机械类型后返回数据
    private ReturnTypeEntity returnTypeEntity;
    //械详情实体
    private AddMachineOutEntity addMachineOutEntity = new AddMachineOutEntity();
    //一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    //二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    //三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    private int cityPosition1;//城市一级位置标记
    private int cityPosition2;//城市二级位置标记
    private int cityPosition3;//城市三级位置标记
    private int unitPosition;//单位选择后位置标记
    private Date today;
    private Calendar selectedDate = Calendar.getInstance();
    ;
    private String titleString;
    private Gson gson;
    private boolean isUpdate = false;
    @Inject
    MachinePublishOutModel viewModel;

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MachinePublishOutActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    public static void start(Context context, String id) {
        Intent intent = new Intent();
        intent.setClass(context, MachinePublishOutActivity.class);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置沉浸式状态栏的上移问题
        setTileImmerse(true);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(MachinePublishOutActivity.this, R.layout.activity_machine_publish_out);
        binding.setViewModel(viewModel);
        binding.topLayout.titleView.setText("机械出租发布");
        binding.topLayout.ivBack.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.itemTvPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.itemTvWork.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.itemTvPrice.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.itemTvDriverAge.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.itemTvDriverAge.setMaxSize(2);
        binding.itemTvDrivingAge.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.itemTvDrivingAge.setCheck(2, 1);
        binding.itemTvSl.setOnWholeItemClickListener(this);
        binding.itemMap.setOnWholeItemClickListener(this);
        binding.itemTvAttribute.setOnWholeItemClickListener(this);
        binding.itemTvType.setOnWholeItemClickListener(this);
        binding.itemTvTime.setOnWholeItemClickListener(this);
        binding.itemTvDriver.setOnWholeItemClickListener(this);
        binding.itemTvUnit.setOnClickListener(this);
        binding.itemTvService.setOnWholeItemClickListener(this);
        binding.itemTvInvoice.setOnWholeItemClickListener(this);
        binding.itemTvInvoiceGg.setOnWholeItemClickListener(this);
        binding.itemTvServicer.setOnWholeItemClickListener(this);
        binding.itemTvInvoice.setOnWholeItemClickListener(this);
        binding.itemTvAllowTime.setOnWholeItemClickListener(this);
        binding.itemTvModel.onTextChange(s -> {
            if ("".equals(binding.itemTvType)) {
                titleString = "出租 " + binding.itemTvBrand.getContent() + "/" + binding.itemTvModel.getContent();
            } else {
                titleString = "出租 " + binding.itemTvType.getContent().substring(binding.itemTvType.getContent().indexOf("-") + 1) + "/" + binding.itemTvBrand.getContent() + "/" + binding.itemTvModel.getContent();
            }
            binding.include.tvTitleDefault.setText(titleString);
        });
        binding.itemTvBrand.onTextChange(s -> {
            if ("".equals(binding.itemTvType)) {
                titleString = "出租 " + binding.itemTvBrand.getContent() + "/" + binding.itemTvModel.getContent();
            } else {
                titleString = "出租 " + binding.itemTvType.getContent().substring(binding.itemTvType.getContent().indexOf("-") + 1) + "/" + binding.itemTvBrand.getContent() + "/" + binding.itemTvModel.getContent();
            }
            binding.include.tvTitleDefault.setText(titleString);
        });
//        binding.sw.setOnCheckedChangeListener((compoundButton, b) -> {
//            if (b) {
//                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setDriver(b);
//            } else {
//                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setDriver(b);
//            }
//        });
        binding.cb.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setNegotiable("1");
                binding.itemTvPrice.setVisibility(View.GONE);
                binding.itemTvUnit.setVisibility(View.GONE);
                binding.cb.setText("您已选择面议，再次点击退出面议");
            } else {
                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setNegotiable("0");
                binding.itemTvPrice.setVisibility(View.VISIBLE);
                binding.itemTvUnit.setVisibility(View.VISIBLE);
                binding.cb.setText("面议");
            }
        });
//        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setDriver(false);
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setNegotiable("0");
        binding.nS.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        binding.nS.setFocusable(true);
        binding.nS.setFocusableInTouchMode(true);
        binding.nS.setOnTouchListener((v, event) -> {
            v.requestFocusFromTouch();
            return false;
        });
        gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
        if (getIntent() != null && !TextUtils.isEmpty(getIntent().getStringExtra("id"))) {
            viewModel.getMachineOutDetailModel(getIntent().getStringExtra("id"));
        }
    }

    @Override
    protected void init() {
        urls = new ArrayList<>();
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        fileList = new ArrayList<>();

        adapter = new ImageAdapter(this, null, null, 5);
        binding.recyclerView.setLayoutManager(new GridLayoutManager(MachinePublishOutActivity.this, 4));
        binding.recyclerView.setAdapter(adapter);
        driverDatas = new ArrayList<>();
        //是否带驾驶员（0:是;1:否）
        PickSelectEntity dentity = new PickSelectEntity();
        dentity.setNo("1");
        dentity.setProjectscale("是");
        PickSelectEntity dentity1 = new PickSelectEntity();
        dentity1.setNo("0");
        dentity1.setProjectscale("否");
        driverDatas.add(dentity);
        driverDatas.add(dentity1);

        //是否选择发票（0:是;1:否）
        invoiceDatas = new ArrayList<>();
        invoiceDatas.add(new PickSelectEntity("1", "是"));
        invoiceDatas.add(new PickSelectEntity("0", "否"));
        //发票类型
        invoiceGGDatas = new ArrayList<>();
        invoiceGGDatas.add(new PickSelectEntity("0", "普通发票"));
        invoiceGGDatas.add(new PickSelectEntity("1", "专用发票"));

        initDefault();
    }

    //设置默认参数
    private void initDefault() {
        binding.itemTvInvoice.setContent("是");
        binding.itemTvInvoiceGg.setContent("普通发票");
        binding.itemTvDriver.setContent("是");
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setDriver("1");
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setNeedInvoice("1");
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setInvoiceType("0");
        viewModel.getMachinePriceModelInit();
        viewModel.getLeaseRate();//税率
    }

    public void addSucc() {
//        MToast.showToast(this, "发布成功");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.MACHINE_PUBLISH_DATA, "");
        SuccessEntity successEntity = new SuccessEntity();
        successEntity.setType(SUCC_MACHINE_OUT);
        successEntity.setButtonText("确定");
        successEntity.setTitle("发布成功");
        successEntity.setContent("您发布信息已提交成功，请前往机械发布页面查看");
        CommitSuccessActivity.start(this, successEntity);
    }

    //图片单张上传
    public void uploadRefresh(String url, int type) {
        uploadImgList.add(url);
        if (currentImgNum + 1 == imgTotal) {
            uploadImgSuccess(uploadImgList, type);
        } else {
            currentImgNum++;
            viewModel.uploadMutiFileModel(adapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
        }
    }

    //图片上传成功回调
    public void uploadImgSuccess(List<String> urls, int type) {
        //拼接图片url
        List<String> urlList = new ArrayList<>();
        for (int i = 0; i < urls.size(); i++) {
            urlList.add(urls.get(i));
        }

        if (type == 0) {
            if (addMachineOutEntity.getPictures() != null) {
                addMachineOutEntity.getPictures().addAll(urlList);
                urlList.clear();
                urlList.addAll(addMachineOutEntity.getPictures());
            }
        }
        //addDeviceEntity.setPictures(urlList);
        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setPictures(urlList);

        //判断是新增还是编辑
        if (binding.itemTvAttribute.getContent().equals("该类型无属性")) {
            ArrayList<PublicAttrEntity> publicAttrEntities = new ArrayList<>();
            viewModel.addMachineOutEntity.get().setAttrList(publicAttrEntities);
        }
        if (!isUpdate) {
            viewModel.addMachineOutModel();
        } else {
            viewModel.editMachineOutModel();
        }
    }

    public void showEditView(AddMachineOutEntity addMachineOutEntity) {
        isUpdate = true;
        this.addMachineOutEntity = addMachineOutEntity;
        viewModel.addMachineOutEntity.set(addMachineOutEntity);
        //机械类型
        if (!TextUtils.isEmpty(addMachineOutEntity.getFirstName())) {
            binding.itemTvType.setContent(addMachineOutEntity.getFirstName() + "-" + addMachineOutEntity.getSecondName());
        }

        if (!TextUtils.isEmpty(addMachineOutEntity.getBuyTime())) {
            //购机时间  此处时间戳为10位
            selectedDate.setTime(new Date(Long.parseLong(addMachineOutEntity.getBuyTime()) * 1000L));
            binding.itemTvTime.setContent(addMachineOutEntity.getBuyTime());
        }

        //是否面议
        if ("1".equals(addMachineOutEntity.getNegotiable())) {
            binding.cb.setChecked(true);
            binding.cb.setText("您已选择面议，再次点击退出面议");
            binding.itemTvPrice.setVisibility(View.GONE);
            binding.itemTvUnit.setVisibility(View.GONE);
        } else {
            binding.cb.setChecked(false);
            binding.cb.setText("面议");
            binding.itemTvPrice.setVisibility(View.VISIBLE);
            binding.itemTvUnit.setVisibility(View.VISIBLE);
        }

        if ("1".equals(addMachineOutEntity.getNeedInvoice())) {
            binding.itemTvInvoice.setContent("是");
            binding.itemTvInvoiceGg.setVisibility(View.VISIBLE);
            binding.itemTvSl.setVisibility(View.VISIBLE);
            binding.itemTvSl.setContent(addMachineOutEntity.getTariff()+"%");
            if ("0".equals(addMachineOutEntity.getInvoiceType())) {
                binding.itemTvInvoiceGg.setContent("普通发票");
            } else {
                binding.itemTvInvoiceGg.setContent("专用发票");
            }
        } else {
            binding.itemTvInvoice.setContent("否");
            binding.itemTvInvoiceGg.setVisibility(View.GONE);
            binding.itemTvSl.setVisibility(View.GONE);
        }

        if ("1".equals(addMachineOutEntity.getDriver())) {
            binding.itemTvDriver.setContent("是");
            binding.itemTvDriverAge.setVisibility(View.VISIBLE);
            binding.itemTvDrivingAge.setVisibility(View.VISIBLE);
        } else {
            binding.itemTvDriver.setContent("否");
            binding.itemTvDriverAge.setVisibility(View.GONE);
            binding.itemTvDrivingAge.setVisibility(View.GONE);
        }

        if (TextUtils.isEmpty(addMachineOutEntity.getAddressDetail())) {
            binding.etDetailAddress.setText(addMachineOutEntity.getTaskAddr());
        } else {
            binding.etDetailAddress.setText(addMachineOutEntity.getAddressDetail());
        }

        binding.itemTvServicer.setContent(addMachineOutEntity.getCustomerServiceName());
        //价格单位
        binding.itemTvUnit.setText(addMachineOutEntity.getPriceUnitName());
        //服务范围
        binding.itemTvService.setContent(addMachineOutEntity.getProvince() + addMachineOutEntity.getCity() + addMachineOutEntity.getDistrict());
        //机械属性
//        attrEntity.setNo(addMachineOutEntity.getAttrList2().get(0).getNo());
//        attrEntity.setName(addMachineOutEntity.getAttrList2().get(0).getName());
        binding.include.tvTitleDefault.setText(addMachineOutEntity.getTitle());
        binding.include.itemTvTitleEdit.setEditContent(addMachineOutEntity.getTitle());
        if (addMachineOutEntity.getAttrList() != null) {
            binding.itemTvAttribute.setContent("已选择");
        }

        //图片
        if (addMachineOutEntity.getPictures().size() > 0) {
            adapter.setNetImgList(addMachineOutEntity.getPictures());
        }

        if (!TextUtils.isEmpty(addMachineOutEntity.getWorkStartTime()) && !TextUtils.isEmpty(addMachineOutEntity.getWorkEndTime())) {
            binding.itemTvAllowTime.setContent(MDateUtil.getByTimestamp(Long.parseLong(addMachineOutEntity.getWorkStartTime()), MDateUtil.Format.FORMART6.name)
                    + "-" + MDateUtil.getByTimestamp(Long.parseLong(addMachineOutEntity.getWorkEndTime()), MDateUtil.Format.FORMART6.name));
        }
    }

    public void getMachineTypeSucc(List<PublicTypeEntity<List<PublicTypeEntity>>> datas) {
        this.publicTypeEntityList = datas;
        if (intent == null) {
            intent = new Intent();
            bundle = new Bundle();
        }
        bundle.putSerializable("publicTypeEntityList", (Serializable) publicTypeEntityList);
        bundle.putInt("type", EVENT_PUBLISH_MACHINE_RETURN);
        intent.putExtras(bundle);
        PublicPublishTypeActivity.start(this, intent);
    }

    public void getMachineArrtSucc(List<FilterEntity<List<FilterEntity>>> list) {
        if (list == null || list.size() == 0) {
            binding.itemTvAttribute.setContent("该类型无属性");
            return;
        }
        attrList = list;
        Intent intent = new Intent(MachinePublishOutActivity.this, PublicPublishAttributeActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("list", (Serializable) list);
        bundle.putSerializable("attributesEntityList", (Serializable) viewModel.addMachineOutEntity.get().getAttrList());
        bundle.putInt("type", EVENT_PUBLISH_MACHINE_ATTR);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 点击获取租赁价格单位
     *
     * @param dictEntityList
     */
    public void showUnitPop(List<DictEntity> dictEntityList) {
        this.dictEntityList = dictEntityList;
        showUnitPop();
    }

    /**
     * 初始化获取
     */
    public void InitUnitData(List<DictEntity> data) {
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                DictEntity entity = new DictEntity();
                entity.setNo(data.get(i).getNo());
                entity.setName(data.get(i).getName());
                dictEntityListnew.add(entity);
            }
            binding.itemTvUnit.setText(data.get(0).getName());
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setPriceUnitNo(data.get(0).getNo());
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setPriceUnitName(data.get(0).getName());
        }

    }


    //服务范围
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressWarnings("unchecked")
    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(MachinePublishOutActivity.this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setDistrict(opt3.get(options1).get(options2).get(options3).getName());
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.itemTvService.setContent(content);
            binding.etDetailAddress.setText("");
            binding.etDetailAddress.setHint("请输入详细地址（必选）");
            cityPosition1 = options1;
            cityPosition2 = options2;
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setProvinceNo(addressEntityList.get(options1).getNo());
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setCityNo(opt2.get(options1).get(options2).getNo());
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setProvince(addressEntityList.get(options1).getName());
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setCity(opt2.get(options1).get(options2).getName());
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    private void showUnitPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(MachinePublishOutActivity.this, (options1, options2, options3, v) -> {
            String content = dictEntityList.get(options1).getName();
            binding.itemTvUnit.setText(content);
            unitPosition = options1;
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setPriceUnitNo(dictEntityList.get(options1).getNo());
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setPriceUnitName(dictEntityList.get(options1).getName());
        }).build();
        businessOption.setPicker(dictEntityList);
        businessOption.setSelectOptions(unitPosition);
        businessOption.show();
    }

    //时间选择器
    public void showTimePop() {
        TimePickerView timePicker = new TimePickerBuilder(MachinePublishOutActivity.this, (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
            String format = sdf.format(date);
            if (today == null)
                today = new Date();
            int compareTo = today.compareTo(date);
            if (compareTo == -1) {
                Toast.makeText(MachinePublishOutActivity.this, "请选择小于今天的日期", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    binding.itemTvTime.setContent(format);
                    selectedDate.setTime(date);
                    Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setBuyTime(format + "");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).setType(new boolean[]{true, false, false, false, false, false}).build();
        timePicker.show();
        timePicker.setDate(selectedDate);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.item_tv_unit:
                Log.d("item_tv_unit", "点击了");
                if (dictEntityList != null) {
                    showUnitPop();
                } else {
                    viewModel.getMachinePriceModel();
                }
                break;
            case R.id.next_view:
                if (TextUtils.isEmpty(binding.itemTvType.getContent())) {
                    MToast.showToast(MachinePublishOutActivity.this, "请选择机械类型");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvBrand.getContent())) {
                    MToast.showToast(MachinePublishOutActivity.this, "请填写机械品牌");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvModel.getContent())) {
                    MToast.showToast(MachinePublishOutActivity.this, "请填写出厂型号");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvTime.getContent())) {
                    MToast.showToast(MachinePublishOutActivity.this, "请选择购机时间");
                    return;
//                } else if (TextUtils.isEmpty(binding.itemTvWork.getContent())) {
//                    MToast.showToast(MachinePublishOutActivity.this, "请填写工作时长");
//                    return;
                }/* else if (TextUtils.isEmpty(binding.itemTvDriver.getContent())) {
                    MToast.showToast(MachinePublishOutActivity.this, "请选择是否自带驾驶员");
                    return;
                }*/ else if (TextUtils.isEmpty(binding.itemTvUnit.getText()) && !binding.cb.isChecked()) {
                    MToast.showToast(MachinePublishOutActivity.this, "请选择价格单位");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvPrice.getText()) && !binding.cb.isChecked()) {
                    MToast.showToast(MachinePublishOutActivity.this, "请选择租赁价格");
                    return;
//                } else if (TextUtils.isEmpty(binding.itemTvService.getContent())) {
//                    MToast.showToast(MachinePublishOutActivity.this, "请选择服务范围");
//                    return;
                } else if (TextUtils.isEmpty(binding.itemTvAttribute.getContent())) {

                    MToast.showToast(MachinePublishOutActivity.this, "请选择机械属性");
                    return;
                } else if (adapter.getUrls().size() == 0) {
                    MToast.showToast(MachinePublishOutActivity.this, "请选择图片");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvPerson.getContent())) {
                    MToast.showToast(MachinePublishOutActivity.this, "请填写联系人姓名");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvPhone.getContent())) {
                    MToast.showToast(MachinePublishOutActivity.this, "请填写联系电话");
                    return;
//                }
//                else if (!CheckUtils.isPhoneNumberValid(binding.itemTvPhone.getContent())) {
//                    Toast.makeText(this, "请填写正确的联系电话", Toast.LENGTH_SHORT).show();
//                    return;
                } else if (TextUtils.isEmpty(binding.etDetailAddress.getText())) {
                    Toast.makeText(this, "请填写详细地址", Toast.LENGTH_SHORT).show();
                    return;
//                } else if (TextUtils.isEmpty(binding.itemTvRepairRemake.getContent())) {
//                    Toast.makeText(this, "请输入维修费用说明", Toast.LENGTH_SHORT).show();
//                    return;
//                } else if (TextUtils.isEmpty(binding.itemTvFuelRemake.getContent())) {
//                    Toast.makeText(this, "油料费用说明", Toast.LENGTH_SHORT).show();
//                    return;
                }

//                if ("是".equals(binding.itemTvDriver.getContent())) {}
                if (!TextUtils.isEmpty(binding.itemTvDriverAge.getContent())) {
                    if (Double.parseDouble(binding.itemTvDriverAge.getContent()) < 16 || Double.parseDouble(binding.itemTvDriverAge.getContent()) > 60) {
                        Toast.makeText(this, "年龄必须在16至60之间", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (!TextUtils.isEmpty(binding.itemTvDrivingAge.getContent())) {
                    if (Double.parseDouble(binding.itemTvDrivingAge.getContent()) > 42) {
                        Toast.makeText(this, "驾龄必须在0至42之间", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                if ("是".equals(binding.itemTvInvoice.getContent())) {
                    if (TextUtils.isEmpty(binding.itemTvSl.getContent())) {
                        Toast.makeText(this, "请选择税率", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                if (binding.cb.isChecked()) {
                    viewModel.addMachineOutEntity.get().setRentalPrice("0");
                }
                viewModel.addMachineOutEntity.get().setRepairRemake(binding.itemTvRepairRemake.getContent());
                viewModel.addMachineOutEntity.get().setFuelRemake(binding.itemTvFuelRemake.getContent());
                viewModel.addMachineOutEntity.get().setDriverAge(binding.itemTvDriverAge.getContent());
                viewModel.addMachineOutEntity.get().setDrivingAge(binding.itemTvDrivingAge.getContent());

                viewModel.addMachineOutEntity.get().setDescribe(binding.cfkEditView.getEditContent());

                String title = binding.include.itemTvTitleEdit.getEditContent();
                if (TextUtils.isEmpty(title)) {//如果自定义标题为空,则上传默认标题
                    viewModel.addMachineOutEntity.get().setTitle(binding.include.tvTitleDefault.getText().toString());
                } else {
                    viewModel.addMachineOutEntity.get().setTitle(title);
                }

                if (adapter.getFileList().size() != 0) {
                    imgTotal = adapter.getFileList().size();
                    viewModel.uploadMutiFileModel(adapter.getFileList().get(currentImgNum), 0, currentImgNum + 1);
                } else {
                    uploadImgSuccess(adapter.getUrls(), 1);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                fileList.clear();
                urls.clear();
                for (LocalMedia localMedia : selectList) {
                    File file = new File(localMedia.getRealPath());
                    fileList.add(file);
                    urls.add(localMedia.getRealPath());
                }
                adapter.setDatas(selectList, urls);
                adapter.setFileList(fileList);
            }
        }
        if (requestCode == 255) {
            if (data == null) {
                return;
            }
            double lat = data.getDoubleExtra(SelectAddressActivity.LATITUDE, 0);
            double lon = data.getDoubleExtra(SelectAddressActivity.LONGTITUDE, 0);
            String address = data.getStringExtra(SelectAddressActivity.CURRENT_POSITION);
            binding.etDetailAddress.setText(address + "");
            viewModel.addMachineOutEntity.get().setLatitude(lat + "");
            viewModel.addMachineOutEntity.get().setLongitude(lon + "");
            viewModel.addMachineOutEntity.get().setAddressDetail(address + "");
            viewModel.addMachineOutEntity.get().setTaskAddr(address + "");
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_tv_driver:
                if (null != driverDatas && driverDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(MachinePublishOutActivity.this, (options1, options2, options3, v) -> {
                        String content = driverDatas.get(options1).getProjectscale();
                        binding.itemTvDriver.setContent(content);
                        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setDriver(driverDatas.get(options1).getNo());
                        if ("否".equals(content)) {
                            binding.itemTvDriverAge.setVisibility(View.GONE);
                            binding.itemTvDrivingAge.setVisibility(View.GONE);
                        } else {
                            binding.itemTvDriverAge.setVisibility(View.VISIBLE);
                            binding.itemTvDrivingAge.setVisibility(View.VISIBLE);
                        }
                    }).build();
                    businessOption.setPicker(driverDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_invoice://选择发票
                if (null != invoiceDatas && invoiceDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(MachinePublishOutActivity.this, (options1, options2, options3, v) -> {
                        String content = invoiceDatas.get(options1).getProjectscale();
                        binding.itemTvInvoice.setContent(content);
                        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setNeedInvoice(invoiceDatas.get(options1).getNo());
                        if ("否".equals(content)) {
                            binding.itemTvInvoiceGg.setVisibility(View.GONE);
                            binding.itemTvSl.setVisibility(View.GONE);
                        } else {
                            binding.itemTvInvoiceGg.setVisibility(View.VISIBLE);
                            binding.itemTvSl.setVisibility(View.VISIBLE);
                            binding.itemTvSl.setContent("");//默认清空数据,重新填写
                        }
                    }).build();
                    businessOption.setPicker(invoiceDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_invoice_gg:
                if (null != invoiceGGDatas && invoiceGGDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(MachinePublishOutActivity.this, (options1, options2, options3, v) -> {
                        String content = invoiceGGDatas.get(options1).getProjectscale();
                        binding.itemTvInvoiceGg.setContent(content);
                        Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setInvoiceType(invoiceGGDatas.get(options1).getNo());
                    }).build();
                    businessOption.setPicker(invoiceGGDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_sl://税率
                if (null != tariffDatas && tariffDatas.size() > 0) {
                    OptionsPickerView businessOption = new OptionsPickerBuilder(MachinePublishOutActivity.this, (options1, options2, options3, v) -> {
                        String content = tariffDatas.get(options1).getProjectscale();
                        binding.itemTvSl.setContent(content);
                        viewModel.addMachineOutEntity.get().setTariff(tariffDatas.get(options1).getNo());
                    }).build();
                    businessOption.setPicker(tariffDatas);
                    businessOption.setSelectOptions(0);
                    businessOption.show();
                }
                break;
            case R.id.item_tv_allow_time:
                TimeRangePopWindow4 timeRangePopWindow4 = new TimeRangePopWindow4(getActivity());
                timeRangePopWindow4.setOnTimeCallBack(new TimeRangePopWindow4.OnTimeCallBack() {

                    @Override
                    public void result(long startTime, long endTime, String content) {
                        binding.itemTvAllowTime.setContent(content);
                        viewModel.addMachineOutEntity.get().setWorkStartTime(String.valueOf(startTime));
                        viewModel.addMachineOutEntity.get().setWorkEndTime(String.valueOf(endTime));
                        timeRangePopWindow4.dismiss();
                    }
                });
                timeRangePopWindow4.showAtLocation(binding.mainLayout, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//                timeRangePopWindow4.setBgView(binding.grayLayout);
//                timeRangePopWindow4.showPopwindow(binding.grayLayout);
                break;
            case R.id.item_tv_servicer:
                if (this.serviceEntities == null) {
                    viewModel.getCustomerOrgDatas();
                } else {
                    if (null != serviceEntities && serviceEntities.size() > 0) {
                        OptionsPickerView businessOption = new OptionsPickerBuilder(MachinePublishOutActivity.this, (options1, options2, options3, v) -> {
                            String content = serviceEntities.get(options1).getProjectscale();
                            binding.itemTvServicer.setContent(content);
                            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setCustomerServiceId(serviceEntities.get(options1).getNo());

                        }).build();
                        businessOption.setPicker(serviceEntities);
                        businessOption.setSelectOptions(0);
                        businessOption.show();
                    }
                }
                break;
            case R.id.item_map:
                if (!TextUtils.isEmpty(binding.itemTvService.getContent())) {
                    //跳转详细地址界面
                    viewModel.getLocationLL(viewModel.addMachineOutEntity.get().getProvinceNo(), viewModel.addMachineOutEntity.get().getCityNo(), viewModel.addMachineOutEntity.get().getAreaNo());
                } else {
                    MToast.showToast(this, "请选择所在地区");
                }
                break;
            case R.id.item_tv_type:
                if (publicTypeEntityList != null) {
                    if (intent == null) {
                        intent = new Intent();
                        bundle = new Bundle();
                    }
                    bundle.putSerializable("publicTypeEntityList", (Serializable) publicTypeEntityList);
                    bundle.putInt("type", EVENT_PUBLISH_MACHINE_RETURN);
                    intent.putExtras(bundle);
                    PublicPublishTypeActivity.start(this, intent);
                } else {
                    viewModel.getMachineTypeModel();
                }

                break;
            case R.id.item_tv_attribute:
                if (attrList != null) {
                    getMachineArrtSucc(attrList);
                } else {
                    if (returnTypeEntity != null) {
                        viewModel.getMachineDictModel(returnTypeEntity.getFirstNo(), returnTypeEntity.getSecondNo());
                    } else if (addMachineOutEntity != null && !TextUtils.isEmpty(addMachineOutEntity.getFirstCategory()) && !TextUtils.isEmpty(addMachineOutEntity.getSecondCategory())) {
                        viewModel.getMachineDictModel(addMachineOutEntity.getFirstCategory(), addMachineOutEntity.getSecondCategory());
                    } else {
                        MToast.showToast(MachinePublishOutActivity.this, "请选先选择机械类型");
                    }
                }
                break;
            //TODO zkw 出厂型号手输
            //            case R.id.item_tv_model:
//                if (modelList != null) {
//                    showModelPop();
//                } else {
//                    if (returnTypeEntity != null) {
//                        viewModel.getMachineDictModel("1", returnTypeEntity.getFirstNo(), returnTypeEntity.getSecondNo());
//                    } else if (!TextUtils.isEmpty(addMachineOutEntity.getFirstCategory()) && !TextUtils.isEmpty(addMachineOutEntity.getSecondCategory())) {
//                        viewModel.getMachineDictModel("1", addMachineOutEntity.getFirstCategory(), addMachineOutEntity.getSecondCategory());
//                    } else {
//                        MToast.showToast(MachinePublishOutActivity.this, "请选先选择机械类型");
//                    }
//                }
//                break;
            case R.id.item_tv_time:
                showTimePop();
                break;
            /*case R.id.item_tv_driver:
                if (payTypeList != null) {
                    showDriverPop();
                } else {
                    setDrvie();
                }
                break;*/
            case R.id.item_tv_service:
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MachinePublishEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_PUBLISH_MACHINE_OUT_EDIT) {
            String id = (String) event.getMessageData();
            viewModel.getMachineOutDetailModel(id);
            EventBus.getDefault().removeStickyEvent(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReturnEvent(MachinePublishEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_PUBLISH_MACHINE_RETURN) {
            returnTypeEntity = (ReturnTypeEntity) event.getMessageData();
            binding.itemTvType.setContent(returnTypeEntity.getFirstName() + "-" + returnTypeEntity.getSecondName());
            titleString = "出租 " + returnTypeEntity.getSecondName() + "/" + binding.itemTvBrand.getContent() + "/" + binding.itemTvModel.getContent();
            binding.include.tvTitleDefault.setText(titleString);
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setFirstCategory(returnTypeEntity.getFirstNo());
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setSecondCategory(returnTypeEntity.getSecondNo());
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setFirstName(returnTypeEntity.getFirstName());
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setSecondName(returnTypeEntity.getSecondName());
            attrList = null;
            binding.itemTvAttribute.setContent("");
        }
    }

    @SuppressWarnings("unchecked")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAttrEvent(PickEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_PUBLISH_MACHINE_ATTR) {
            Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setAttrList((List<PublicAttrEntity>) event.getObject());
            binding.itemTvAttribute.setContent("已选择");
//            publicAttrEntityList = (List<PublicAttrEntity>) event.getObject();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    thread = null;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (addMachineOutEntity != null && addMachineOutEntity.getProvince() != null && addMachineOutEntity.getProvince().equals(addressEntityList.get(x).getName())) {
                cityPosition1 = x;
            }
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (addMachineOutEntity != null) {
            if (addMachineOutEntity.getCity() != null)
                for (int x2 = 0; x2 < opt2.size(); x2++) {
                    if (addMachineOutEntity.getCity().equals(addressEntityList.get(cityPosition1).getChildren().get(x2).getName())) {
                        cityPosition2 = x2;
                        break;
                    }
                }
            if (addMachineOutEntity.getDistrict() != null)
                for (int x3 = 0; x3 < opt3.size(); x3++) {
                    if (addMachineOutEntity.getDistrict().equals(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(x3).getName())) {
                        cityPosition3 = x3;
                        break;
                    }
                }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    //税率
    public void showRate(List<PickSelectEntity> list) {
        tariffDatas = list;
    }

    //客服
    public void getCustomerOrgDataS(List<ServiceEntity> serviceEntities) {
        this.serviceEntities = new ArrayList<PickSelectEntity>();
        for (int i = 0; i < serviceEntities.size(); i++) {
            PickSelectEntity pickSelectEntity = new PickSelectEntity();
            pickSelectEntity.setNo(serviceEntities.get(i).getId());
            pickSelectEntity.setProjectscale(serviceEntities.get(i).getName());
            this.serviceEntities.add(pickSelectEntity);
        }
        if (null != serviceEntities && serviceEntities.size() > 0) {
            OptionsPickerView businessOption = new OptionsPickerBuilder(MachinePublishOutActivity.this, (options1, options2, options3, v) -> {
                String content = this.serviceEntities.get(options1).getProjectscale();
                binding.itemTvServicer.setContent(content);
                Objects.requireNonNull(viewModel.addMachineOutEntity.get()).setCustomerServiceId(this.serviceEntities.get(options1).getNo());
            }).build();
            businessOption.setPicker(this.serviceEntities);
            businessOption.setSelectOptions(0);
            businessOption.show();
        }
    }

    //  返回经纬度信息
    public void getLocationLL(MapLongAndLatEntity data) {
        if (!TextUtils.isEmpty(data.getLat())) {
            if (!TextUtils.isEmpty(data.getLng())) {
                Intent intent = new Intent();
                intent.setClass(this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "详细地址");
                intent.putExtra(SelectAddressActivity.HINT, "请输入地址");
                intent.putExtra(SelectAddressActivity.SAVE_TEXT, "确定");
                intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(data.getLat()));
                intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(data.getLng()));
                startActivityForResult(intent, 255);
            }
        }
    }

}

